package com.lw.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LW
 * @2020/8/19 14:02
 */
public class B {

    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }

        },"B").start();

    }
}
//判断等待，业务，通知
class Data2{
    private int num = 0;
    Lock lock = new ReentrantLock();//替代了synchronized的方法和语句的使用
    Condition condition = lock.newCondition();//取代了对象监视器方法的使用
    //+1
    public void increment(){
        lock.lock();


        try {
            //多线程判断用while不用if   两个线程以上线程就不安全了
            //while 防止虚假唤醒
            while (num!=0){
                //等待
                condition.await();//替代了wait方法
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"-->"+num);
            //通知其他线程，+1完毕
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public synchronized void decrement(){
        lock.lock();

        try {
            while (num==0){
                //等待
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"-->"+num);
            //通知其他线程，-1完毕
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
